/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-09-29
 * Time: 10:34
 */

//生产者消费者模型、实现一个阻塞队列（循环数组来实现）

class MyBlockingQueue {
    private String[] items = new String[1000];

    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;
    public void put (String elem) throws InterruptedException {
        synchronized (this) {
            while (size >= items.length) {
                //队列满，开始阻塞等待。
                System.out.println("队列满，开始阻塞等待！！！");
                this.wait();
                //return;
            }
            items[tail] = elem;
            tail ++;
            if (tail >= items.length) {
                tail = 0;
            }
            size ++;
            this.notify();
        }
    }

    public String take () throws InterruptedException {
        synchronized (this) {
            //判断队列是否为空，若为空则不能出队列。
            while (size == 0) {
                //队列空，开始阻塞等待
                System.out.println("队列空，开始阻塞等待！！");
                this.wait();
                //return null;
            }
            String elem = items[head];
            head ++;
            if (head >= items.length) {
                head = 0;
            }
            size --;
            //使用 notify 来唤醒队列满的阻塞情况。
            this.notify();
            return elem;
        }
    }
}

public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
/*
        MyBlockingQueue queue = new MyBlockingQueue();
        queue.put("aaa");
        queue.put("bbb");
        queue.put("ccc");
        queue.put("kkk");

        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
*/

        MyBlockingQueue queue = new MyBlockingQueue();
        //生产者
        Thread t1 = new Thread(() ->{
            int count = 0;
            while (true) {
                try {
                    queue.put(count + "");
                    System.out.println("生产元素：" + count);
                    count ++;
                    //Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //消费者
        Thread t2 = new Thread(() -> {
           while (true) {
               try {
                   String count = queue.take();
                   System.out.println("消费元素：" + count);
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        t1.start();
        t2.start();
    }
}
